var express = require('express');
var router = express.Router();
const RelationType = require('../models/RelationType');
const Relation = require('../models/Relation');
var tools = require('../utils/tools')

router.get('/', function (req, res, next) {
  RelationType.find((err, docs) => {
    if (err) return tools.handleError(res, err);
    return res.json({ status: 'success', data: docs })
  })
});

router.get('/page', function (req, res, next) {
  RelationType.page(tools.queryResolver(req.query), req.query.page, req.query.size, result => {
    res.json({ status: 'success', data: result.docs, pageable: result.pageable })
  })
});

router.get('/:id', function (req, res, next) {
  RelationType.findById(req.params.id, (err, doc) => {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success', data: doc })
  })
});


router.delete('/:id', async function (req, res, next) {

  const relationCount = await Relation.count({ type: req.params.id })
  if (relationCount > 0) {
    return tools.handleError(res, '请先删除模型的关联关系, 共 ' + relationCount + ' 个');
  }

  RelationType.findOneAndDelete({ _id: req.params.id, buildin: false }, function (err, doc) {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success' })
  });
});

router.post('/', async function (req, res, next) {
  const data = { ...req.body, buildin: false }
  RelationType.create(data, function (err, doc) {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success', data: doc })
  });
});

router.put('/:id', async function (req, res, next) {
  const { name, srcdesc, destdesc } = req.body
  RelationType.findByIdAndUpdate(req.params.id, { $set: { name, srcdesc, destdesc } }, { new: true }, function (err, doc) {
    if (err) return tools.handleError(res, err);
    res.json({ status: 'success', data: doc })
  });
});


module.exports = router;
